var baseUrl = 'http://localhost:9001';
var loginUser = JSON.parse(sessionStorage.getItem('member'));
// 消息模板（改为显示预约信息）
var msgTemplate = '\
<li class="msg clear">\
    <div class="left">\
        <img class="head" src="./img/icon/gerenzhongxin-zhihui.svg" />\
    </div>\
    <div class="right">\
        <div class="contact clear">\
            <div class="name left">{{memberName}}</div>\
            <div class="time right">{{courseTime}}</div>\
        </div>\
        <div class="content">{{courseName}}就要开始了</div>\
    </div>\
</li>';

$(function() {
    loadReservations();
});

// 加载预约信息作为消息
function loadReservations() {
    var token = sessionStorage.getItem('token');

    if (!loginUser || !token) {
        showError('请先登录');
        return;
    }

    $.ajax({
        url: baseUrl + '/fore/reservations/' + loginUser.id,
        type: 'get',
        dataType: 'json',
        beforeSend: function(request) {
            request.setRequestHeader("token", token);
        },
        success: function(result) {
            if (result.code == 200) {
           console.log(result.data)
                renderReservations(result.data);
            } else {
                showError(result.msg || '加载预约信息失败');
            }
        },
        error: function(xhr) {
            if (xhr.status == 401) {
                showError(xhr.responseJSON?.msg || '请先登录');
            } else {
                showError('请求失败，请稍后重试');
            }
        }
    });
}

// 渲染预约列表
function renderReservations(reservations) {
    var $list = $('.msg-list');
    $list.empty();

    if (!reservations || reservations.length === 0) {
        $list.append('<li class="empty-tip">暂无预约记录</li>');
        return;
    }

    $.each(reservations, function(index, reserve) {
        var html = msgTemplate
            .replace('{{memberName}}', reserve.memberName)
            .replace('{{courseTime}}', formatTime(reserve.courseTime))
            .replace('{{courseName}}', reserve.courseName)
        $list.append(html);
    });
}


// 格式化时间显示
function formatTime(timeStr) {
    if (!timeStr) return '';
    var date = new Date(timeStr);
    return date.toLocaleString([], {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 显示错误信息
function showError(msg) {
    $('body').append('<div class="error-toast">' + msg + '</div>');
    setTimeout(function() {
        $('.error-toast').remove();
    }, 3000);
}
